<template>
	<div class="fire-box">
		<div class="weather-box" @click="weatherDetail">
			<img :src="imgUrl" alt="" />
		</div>
		<div class="button-box">
			<div class="right-button select" @click="toScreen">火情筛选</div>
			<div class="right-button list" :class="{ listactive: listShow }" @click="showlistPopup">火情列表</div>
		</div>
		<!-- 筛选弹窗 -->
		<van-popup v-model="screenShow" position="right" :style="{ height: '100%', width: '80%' }"> <ScreenPanel @screenQuery="screenQuery" /> </van-popup>
		<!-- 天气详情弹窗 -->
		<van-popup v-model="showWeatherDetail" closeable :close-on-click-overlay="false">
			<div class="poi-title">天气情况</div>
			<div class="weather-content">
				<div class="overView">
					<img :src="imgUrl" alt="" />
					<div class="right">
						<p>
							<span>{{ currentPlace }}</span>
							<span>{{ tRange.low }} / {{ tRange.height }}℃</span>
						</p>
						<p>
							<span>{{ weatherType }}</span>
							<span><img src="/img/weather/humidity.png" alt="" />相对湿度</span>
							<span>{{ humidity }}</span>
						</p>
					</div>
				</div>
				<div class="detail">
					<div class="detailItem" v-for="(item, index) of detailList" :key="index">
						<p class="type">{{ item.type }}</p>
						<img :src="'/img/weather/' + item.img" alt="" />
						<p class="type">{{ item.value }}</p>
					</div>
				</div>
			</div>
		</van-popup>
		<!-- poi详情弹窗 -->
		<van-popup v-model="showPoiDetail" closeable :close-on-click-overlay="false">
			<div class="poi-title">应急要素</div>
			<div class="PoiInfoItem" v-for="(value, key, index) in poiDetail" :key="index">
				<div v-if="value || value === 0" :style="{ background: 'rgba(19,62,76,0.5)', color: '#fff' }">{{ key }}&nbsp;:</div>
				<div :title="value">{{ value }}</div>
			</div>
		</van-popup>
		<!-- 主功能弹窗 -->
		<van-popup class="detailPopup" v-model="listShow" closeable :overlay="false" @closed="popupClose" position="bottom" :style="{ height: popupHeight }">
			<div class="popup-name">{{ showModel ? showModel.name : '' }}</div>
			<!-- 火情列表 -->
			<div v-if="listShow && showModel.name == '火情列表'" class="fire-list">
				<van-collapse v-model="activeNames" v-if="fireList && fireList.length > 0">
					<van-collapse-item v-for="(item, index) in fireList" :key="index" :name="index">
						<template #title>
							<div>
								<span class="added">{{ '+' + item.total }}</span>
								{{ item.time }}
							</div>
						</template>
						<div class="list-content" v-for="(subItem, subIndex) in item.list" :key="subIndex">
							<div class="content-img">
								<img :src="'/img/firepanel/' + subItem.imgName" alt="" />
							</div>
							<div class="content-font">
								<div class="font-title">{{ subItem.title }}</div>
								<div class="font-type">{{ '下垫面类型：' + subItem.type }}</div>
								<div class="font-number">{{ subItem.code ? '编号：' + subItem.code : '' }}</div>
							</div>
							<div class="content-handle">
								<img class="position" src="/img/fire/dingwei.png" @click="flyTo(subItem)" alt="" />
								<div class="detail" @click="showDetail(subItem)">
									详情
									<img src="/img/fire/xiangqing.png" alt="" />
								</div>
							</div>
						</div>
					</van-collapse-item>
				</van-collapse>
				<van-empty v-else image="error" description="暂无内容" />
			</div>
			<!-- 火点详情 -->
			<div v-if="listShow && showModel.name == '火点详情'" class="fire-detail">
				<div class="detail-panel" v-if="detailObj && detailObj.id">
					<p>
						<span>时间：</span>
						<span>{{ detailObj.observeTime }}</span>
					</p>
					<p>
						<span>地名：</span>
						<span>{{ detailObj.place }}</span>
					</p>
					<p v-if="detailObj.distance != 0">
						<span>{{ detailObj.place }}与火点距离：</span>
						<span>{{ detailObj.distance }}</span>
					</p>
					<p v-if="detailObj.direction != 0">
						<span>{{ detailObj.place }}与火点方位角：</span>
						<span>{{ detailObj.direction }}</span>
					</p>
					<p>
						<span>经度：</span>
						<span>{{ detailObj.longitude.toFixed(7) }}</span>
					</p>
					<p>
						<span>纬度：</span>
						<span>{{ detailObj.latitude.toFixed(7) }}</span>
					</p>
					<div v-if="detailObj.elevationAver != 0 && detailObj.intensityG != 0">
						<p>
							<span>高程(平均)：</span>
							<span>{{ detailObj.elevationAver }}</span>
						</p>
						<p>
							<span>强度G：</span>
							<span>{{ detailObj.intensityG }}</span>
						</p>
					</div>
					<div v-if="detailObj.intensityT != 0 && detailObj.hotspot != 0">
						<p>
							<span>强度T：</span>
							<span>{{ detailObj.intensityT }}</span>
						</p>
						<p>
							<span>热点数：</span>
							<span>{{ detailObj.hotspot }}</span>
						</p>
					</div>
					<p>
						<span>行政编码：</span>
						<span>{{ detailObj.adminCode }}</span>
					</p>
					<p v-if="detailObj.repeat != 0">
						<span>疑似重复次数：</span>
						<span>{{ detailObj.repeat }}</span>
					</p>
				</div>
				<div class="detail-panel" v-if="detailObj && detailObj.gfAver != 0">
					<p>
						<span>植被类型：</span>
						<span>{{ detailObj.speciesType }}</span>
					</p>
					<p>
						<span>植被覆盖度(平均)：</span>
						<span>{{ detailObj.gfAver ? detailObj.gfAver + '%' : 0 }}</span>
					</p>
					<p>
						<span>森林：</span>
						<span>{{ detailObj.forestPercent ? detailObj.forestPercent + '%' : 0 }}</span>
					</p>
					<p>
						<span>草地:</span>
						<span>{{ detailObj.lawnPercent ? detailObj.lawnPercent + '%' : 0 }}</span>
					</p>
					<p>
						<span>农田及自然植被:</span>
						<span>{{ detailObj.farm ? detailObj.farm + '%' : 0 }}</span>
					</p>
					<p>
						<span>灌木:</span>
						<span>{{ detailObj.bush ? detailObj.bush + '%' : 0 }}</span>
					</p>
					<p>
						<span>城市或荒漠:</span>
						<span>{{ detailObj.city ? detailObj.city + '%' : 0 }}</span>
					</p>
				</div>
				<div class="charge-person">
					<div v-for="(item, index) in chargePersonArr" :key="index">
						<van-cell-group>
							<van-cell :title="item.xm" :value="item.bgdh">
								<template #label>
									<div>{{ item.dhhm }}</div>
									<div>{{ item.zw ? item.ssdw + ' ' + item.zw : item.ssdw }}</div>
								</template>
							</van-cell>
						</van-cell-group>
					</div>
				</div>
				<div class="detail-handel">
					<!-- <div @click="fireDispose">火情处置</div> -->
					<div @click="fireCouple">火情反馈</div>
					<div @click="assistantAna">辅助分析</div>
				</div>
			</div>
			<div v-if="listShow && showModel.name == '辅助分析'" class="assistant-analysis">
				<div class="popDown" @click="popDown">
					<van-icon :name="popupHeight == '50%' ? 'arrow-down' : 'arrow-up'" />
				</div>
				<div class="detail-panel">
					<p>
						<span>经度：</span>
						<span>{{ detailObj.longitude.toFixed(7) }}</span>
					</p>
					<p>
						<span>纬度：</span>
						<span>{{ detailObj.latitude.toFixed(7) }}</span>
					</p>
					<p>
						<span>时间：</span>
						<span>{{ detailObj.observeTime }}</span>
					</p>
					<p>
						<span>下垫面类型：</span>
						<span>{{ detailObj.vegType }}</span>
					</p>
					<p>
						<span>强度T：</span>
						<span>{{ detailObj.intensityT }}</span>
					</p>
				</div>
				<van-cell-group>
					<van-field v-model="scopeValue" label="半径范围：" placeholder="km" @input="scopeChange">
						<template #button> km </template>
					</van-field>
				</van-cell-group>
				<div class="check-box-group">
					<div class="each-item" v-for="(zitem, zindex) in poiFormated" :key="zindex">
						<van-checkbox class="group-title" v-model="checked[zindex]" shape="square" @change="(bool) => allSelect(bool, zindex)">{{ zitem.label }}</van-checkbox>
						<van-checkbox-group v-model="result[zindex]" :ref="'checkboxGroup' + zindex" @change="(arr) => targetCheck(arr, zitem, zindex)">
							<van-checkbox v-for="(citem, cindex) in zitem.subType" :key="cindex" shape="square" :name="citem.label">{{ citem.label }}</van-checkbox>
						</van-checkbox-group>
					</div>
				</div>
				<div class="brief-report-box">
					<div class="report-button" @click="getPdf">火情简报</div>
				</div>
			</div>
		</van-popup>
		<van-overlay :show="overlayShow" @click="overlayShow = false">
			<div class="wrapper" @click.stop>
				<div class="block" />
			</div>
		</van-overlay>
	</div>
</template>

<script>
/* global viewer Cesium */
import ScreenPanel from './Screen.vue'
import { getFireDetail, searchPOI, getFirePerson, getFirePersonTest, searchPoiDetail, getReportPoi } from '../../api/fire'
import { keyFormate } from '../../util/fireUtils'
import jsrsasign from 'jsrsasign'
import axios from 'axios'
import { Toast } from 'vant'
import dd from 'gdt-jsapi'
import openLink from 'gdt-jsapi/openLink'
let entityModel = []
let circleEntity = null
let poiModel = []
let handler3D = null
export default {
	name: 'firebox',
	components: { ScreenPanel },
	data() {
		return {
			userContentData: null, //登录用户详情
			isPerson: false, // 当前登录用户是否是火点防火人
			newIcon: false, // 是否显示新火点图标
			screenData: null, // 条件筛选参数
			popupHeight: '50%',
			overlayShow: false,
			fireAllInfo: null,
			fireList: [], //火点查询结果
			checked: [false, false, false, false], // poi列表选中状态
			result: [[], [], [], []], // poi列表选中状态
			listShow: false,
			showWeatherDetail: false,
			showPoiDetail: false,
			screenShow: false,
			imgUrl: '/img/weather/duoyun.png',
			showModel: null, // 下方弹框标题
			activeNames: [0], // 火情列表展开
			scopeValue: 3, // 火情范围
			detailObj: null, // 当前查看的火点详情
			selectOptions: [], // poi数据
			poiFormated: [], //格式化之后的POI点集合
			poiDetail: {
				orgName: '县级教育部门',
				proPac: '460000000',
				province: '',
				sclacc: '',
				sid: null,
				sourceCode: undefined,
				statisticy: '2017',
				totalFacul: '30',
				totalStude: '422',
				towPac: '469026105',
				town: '海尾镇',
				type: '幼儿园',
				updateTime: '2020-07-21 00:00:00'
			}, //poi详情
			detailList: [
				{ type: '风向', img: 'fengxiang2.png', value: '东北风2级' },
				{ type: '风速', img: 'fengsu2.png', value: '2m/s' },
				{ type: '气压', img: 'qiya2.png', value: '101kPa' },
				{ type: '降雨量', img: 'jiangyuliang2.png', value: '>10mm/h' },
				{ type: '温度', img: 'wendu2.png', value: '2-18℃' },
				{ type: '天气', img: 'tianqi2.png', value: '多云' },
				{ type: '相对湿度', img: 'xiangduishidu2.png', value: '48%' },
				{ type: '空气质量', img: 'kongqizhiliang2.png', value: '良好' }
			],
			currentPlace: '海口市',
			tRange: { low: 2, height: 18 },
			weatherType: '多云',
			humidity: '48%'
		}
	},
	mounted() {
		document.title = '火情监测'
		let that = this
		async function getUser() {
			//获取accessToken
			// console.log('获取accessToken1')
			let accessTokenData = await axios.get(`${window.baseURL}/api/hzd/gettoken.json`)
			let accessToken = accessTokenData.data.content.data.accessToken
			//获取authCode
			let authCode = ''
			// console.log('accessToken', accessToken)
			// console.log('获取accessToken2')
			dd.getAuthCode({ corpId: '' })
				.then((result) => {
					// console.log('authCode', authCode)
					// console.log(result)
					if (result) {
						authCode = result
					}
				})
				.then(() => {
					//获取用户信息
					axios.post(`${window.baseURL}/api/hzd/getUserinfo`, { access_token: accessToken, auth_code: authCode.code }).then((res) => {
						// console.log('用户信息', res)
						that.userContentData = JSON.parse(res.data.content)
					})
				})
				.catch((err) => {})
		}
		getUser()
		this.initWebSocket()

		this.$nextTick(() => {
			handler3D = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
			handler3D.setInputAction(this.pickeFireEvent, Cesium.ScreenSpaceEventType.LEFT_CLICK)
		})
	},
	beforeDestroy() {
		viewer.entities.removeAll()
	},
	methods: {
		popupClose() {
			if (this.showModel.name == '辅助分析') {
				this.listShow = true
				this.showModel = { name: '火点详情' }
			} else {
				this.listShow = false
				this.showPopup = null
			}
			this.checked = [false, false, false, false]
			this.scopeValue = 3
			this.popupHeight = '50%'
			this.poiFormated = []
			this.hidePOI()
			this.hideCircle()
		},
		showlistPopup() {
			if (this.listShow) {
				this.popupClose()
			} else {
				this.listShow = true
				this.showModel = { name: '火情列表' }
			}
		},
		// 获取条件筛选面板参数
		screenQuery(data) {
			this.screenData = data
			this.websocketsend(data)
			this.screenShow = false
		},
		toScreen() {
			this.screenShow = true
		},
		// 内置跳转，api鉴权失败
		// toScreenSelf() {
		// 	let coid = String(this.userContentData.data.realmId)
		// 	let id = String(this.userContentData.data.accountId)
		// 	// console.log('realmId:', coid)
		// 	// console.log('accountId:', id)
		// 	dd.openPage({
		// 		name: 'Screen', //页面名称
		// 		params: {
		// 			corpId: coid,
		// 			id: id
		// 		}
		// 	})
		// 		.then(() => {})
		// 		.catch(() => {})
		// },
		flyTo(item) {
			viewer.camera.flyTo({
				destination: Cesium.Cartesian3.fromDegrees(item.longitude, item.latitude - 0.05, 20000)
			})
		},
		// 获取防火责任人
		async getFirePersonTest(lat, lon) {
			// console.log('获取防火责任人')
			// let personArr = await getFirePersonTest(lat, lon)
			let personArr = await getFirePerson(lat, lon)
			console.log('防火责任人接口')
			this.chargePersonArr = personArr
			// console.log('accountId', this.userContentData.accountId)
			personArr.forEach((element) => {
				console.log(element)
				if (this.userContentData.accountId == element.id) {
					// if (element.id == 205) {
					this.isPerson = true
					// console.log('是防火责任人')
				}
			})
		},
		async getDetailData(id) {
			let ddata = await getFireDetail(id)
			this.detailObj = ddata
			// 格式化简报信息
			// this.getFireInfo(ddata)
			this.formatedData = keyFormate('fireDetailC', ddata)
		},
		// 火点详情
		showDetail(item) {
			this.getDetailData(item.id).then(() => {
				// console.log('获取detail')
				if (this.detailObj.cityRegion) {
					// console.log('如果有城市id')
					let code = this.getCityCode(this.detailObj.cityRegion)
					this.initWeather(code)
				}
			})
			this.getFirePersonTest(item.latitude, item.longitude)
				.then((res) => {
					console.log(res)
					// console.log('防火责任人true')
					this.listShow = true
					this.showModel = { name: '火点详情' }
				})
				.catch((err) => {
					console.log(err)
					console.log('防火责任人catch')
					this.listShow = true
					this.showModel = { name: '火点详情' }
				})
			// getFirePersonTest(item.latitude, item.longitude)
			// 	.then((res) => {
			// 		this.chargePersonArr = res
			// 		res.forEach((element) => {
			// 			if (this.userContentData.accountId == element.id) {
			// 				this.isPerson = true
			// 			}
			// 		})
			// 	})
			// 	.then(() => {
			// 		this.listShow = true
			// 		this.showModel = { name: '火点详情' }
			// 	})
		},
		// // 格式化简报信息
		// getFireInfo(fireRes) {
		// 	this.reportInfo.fireBase.fireCode = fireRes.code
		// 	this.reportInfo.fireBase.time = fireRes.observeTime.replace('-', '年').replace('-', '月').replace(' ', '日 ').replace(':', '时').replace(':', '分') + '秒'
		// 	this.reportInfo.fireBase.place = fireRes.place
		// 	this.reportInfo.fireBase.lon = fireRes.longitude
		// 	this.reportInfo.fireBase.lat = fireRes.latitude
		// 	this.reportInfo.fireBase.distance = fireRes.distance + 'Km'
		// 	this.reportInfo.fireBase.angle = fireRes.direction + '°'
		// 	this.reportInfo.fireBase.height = fireRes.elevationAver + 'm'
		// 	this.reportInfo.fireBase.hotNum = fireRes.hotspot
		// 	let all = fireRes.gfAver ? fireRes.gfAver + '%' : '未知'
		// 	let senlin = fireRes.forestPercent ? fireRes.forestPercent + '%' : 0
		// 	let caodi = fireRes.lawnPercent ? fireRes.lawnPercent + '%' : 0
		// 	let nongtian = fireRes.farm ? fireRes.farm + '%' : 0
		// 	let guanmu = fireRes.bush ? fireRes.bush + '%' : 0
		// 	let chengshi = fireRes.city ? fireRes.city + '%' : 0
		// 	let veg = `植被覆盖度${all}, 其中森林${senlin},草地${caodi},农田及自然植被${nongtian},灌木${guanmu},城市或荒漠${chengshi}`
		// 	this.reportInfo.fireBase.veg = veg
		// },
		// 展示天气详情
		weatherDetail() {
			if (this.listShow == true && this.showModel.name != '火情列表') {
				this.showWeatherDetail = true
			}
		},
		assistantAna() {
			this.flyTo(this.detailObj)
			this.showModel = { name: '辅助分析' }
			this.showCricle()
		},
		fireCouple() {
			// console.log(encodeURI(JSON.stringify(this.formatedData)))
			let coupleData = encodeURI(JSON.stringify(this.formatedData))
			openLink({
				url: `${window.selfURL}couple?appId=huoqing-e9Zlo4q8P45M47CrnaeERj&type=1&coupleData=${coupleData}&isPenson=${this.isPerson}`
			}).then((res) => {
				console.log(res)
			})
		},
		// 扩散波
		showCricle() {
			if (circleEntity) this.hideCircle()
			if (this.scopeValue <= 0) return
			let data = {
				id: this.detailObj.id,
				imageUrl: require('../../assets/ripple.png'),
				lon: this.detailObj.longitude,
				lat: this.detailObj.latitude,
				height: 0,
				minR: 100,
				maxR: this.scopeValue * 1000,
				deviationR: this.scopeValue * 10
			}
			circleEntity = viewer.entities.add({
				name: '',
				// id: data.id,
				position: Cesium.Cartesian3.fromDegrees(data.lon, data.lat, data.height),
				ellipse: {
					semiMinorAxis: data.maxR,
					semiMajorAxis: data.maxR,
					height: data.height,
					material: new Cesium.ImageMaterialProperty({
						// image: data.imageUrl,
						repeat: new Cesium.Cartesian2(1.0, 1.0),
						transparent: true,
						color: Cesium.Color.RED.withAlpha(0.2)
					})
				}
			})
			this.showPOI(data)
		},
		// 渲染POI点
		async showPOI(data) {
			let poiRes = await searchPOI(data.lon, data.lat, data.maxR)
			this.selectOptions = poiRes
			// 每次更新数据，清除之前的实体
			this.hidePOI()
			poiModel = []
			//添加标记
			for (let item of poiRes) {
				let entity = viewer.entities.add({
					name: item.ppType,
					id: item.ppId,
					position: Cesium.Cartesian3.fromDegrees(item.ppLon, item.ppLat),
					billboard: {
						// image: `./img/poi/${item.ppGroup}_${item.ppType}.png`,
						image: this.poiImgChoose(item.ppGroup, item.ppType),
						scale: 0.8,
						horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
						verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
						heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
						scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0.7),
						disableDepthTestDistance: Number.POSITIVE_INFINITY,
						width: 30,
						height: 30
					},
					entityType: 'poi',
					poiType: item.ppType
				})
				poiModel.push(entity)
			}
			this.poiFormated = this.calPoiNum(poiRes)
			console.log(this.poiFormated)
			this.$nextTick(() => {
				this.checked = [true, true, true, true]
			})
		},
		// 清除POI点
		hidePOI() {
			for (var i = 0; i < poiModel.length; i++) {
				viewer.entities.remove(poiModel[i])
			}
			poiModel = []
		},
		// 统计POI点类型个数
		calPoiNum(data) {
			let arr = []
			let finalArr = []
			data.forEach((ele) => {
				let obj = arr.filter((item) => item.type === ele.ppType)[0] || {}
				if (obj.type) {
					obj.num++
					obj.label = `${obj.type}(${obj.num})`
				} else {
					// 子类
					// obj.icon = `./img/poi/${ele.ppGroup}_${ele.ppType}.png`
					// obj.icon = this.poiImgChoose(ele.ppGroup, ele.ppType)
					obj.type = ele.ppType
					obj.num = 1
					obj.ppGroup = ele.ppGroup
					obj.label = `${obj.type}(${obj.num})`
					arr.push(obj)
				}
			})
			arr.forEach((ele) => {
				let obj = finalArr.filter((item) => item.type === ele.ppGroup)[0] || { subType: [] }
				if (obj.type) {
					obj.totalNum += ele.num
					obj.label = `${obj.type}(${obj.totalNum})`
					obj.subType.push(ele)
				} else {
					// 父类
					obj.icon = ele.icon
					obj.type = ele.ppGroup
					obj.totalNum = ele.num
					obj.label = `${obj.type}(${obj.totalNum})`
					obj.subType.push(ele)
					finalArr.push(obj)
				}
			})
			return finalArr
		},
		// 清除扩散波
		hideCircle() {
			viewer.entities.remove(circleEntity)
			circleEntity = null
		},
		scopeChange(val) {
			// 辅助分析范围输入更改
			if (val) {
				this.showCricle()
				this.checked = [false, false, false, false]
			}
		},
		allSelect(val, ind) {
			this.$refs['checkboxGroup' + ind][0].toggleAll(val)
		},
		targetCheck(val, item, ind) {
			// 控制子目标全选中或全取消时更改父点 的选中状态
			if (val.length == 0) {
				this.$set(this.checked, ind, false)
			}
			if (val.length == item.subType.length) {
				this.$set(this.checked, ind, true)
			}
			let boole = false
			item.subType.forEach((ele) => {
				if (val.indexOf(ele.label) == -1) {
					boole = false
				} else {
					boole = true
				}
				poiModel.forEach((mod) => {
					if (mod.poiType === ele.type) {
						mod.show = boole
					}
				})
			})
		},
		initWeather(mes) {
			let cityCode = mes
			// 获取当前天气情况
			let time = Date.now()
			// 获取火点发生时的天气情况
			let code = 'cityCode=' + cityCode + '&' + 'ts=' + time
			let privateKey =
				'MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKFylef7n6cuemB1Z/Yo853RtbChXtr02Zv+iesJ3H70VuuW8tMPIzCp8n1D1PWgBgRAAtuTU99EPw3eCODr8EeL8+dnyXzLlt03YaKg+pPa9ZEFKtF2bG0xK664JQpJD47lAxuLEqnnX62It1Kd3wjOt30mmviiDZbEyW0zLy39AgMBAAECgYAli4D2ibLrXVjqwSrr2UKsPzZmTOTC/SF1EEjxDqJHKNnk4D34nMLVgJQqkuF9vJjhmKRBfX3KBHQ4bJv6eIvwLMpXyg0jvraErdegir8GkiixanCYT/hdBHNY8h1gMOif1AIYJnFSp2BnxlgJuA3E0d20y/vddv/L+9AKbdtnMQJBANiKEVUOA5p+kJigpPCPO5VSmXCkMQBp4dZ+HZuLOM1pBeFKu8uaSPOpp6E+z6RA2dFbc7z0/Q8M6Fbb1tSv8g0CQQC+3mTbxPASQ3+9e7FAgfcTrGfjK2ss5L4K4a53Gi9OgvFDaoAIAkOnkJAj0T/fmGHdojQswq1bUwmnCJSWDl+xAkBHY01Pgy1A89Tr3JpEDJSSKAcaEaduAXpI4o8URpPVdHhRy/eZqiW+3wG6sSB3gEHPOZ0wgHwlSBYY/KUYvWDJAkA6yVJ1IdXzOhjo6mTwglbwF0S0AhZzcExcG6BZjJYPb2MRqYafcNsXi/3pGjS7EDrsQV4ifx9Xpl6ttIXXJbwxAkBxuncgioNV7lPfdH/xQBTLY7L26Uoi2hATCHXrr0r24V427twRkO0l9sX9CTqMaOxYHzVhWBaeuvrmMnAgBPbo'
			let privateKeyFormat = '-----BEGIN PRIVATE KEY----- ' + privateKey + '-----END PRIVATE KEY-----'
			let signature = new jsrsasign.KJUR.crypto.Signature({
				alg: 'SHA256withRSA',
				prov: 'cryptojs/jsrsa',
				prvkeypem: privateKeyFormat
			})
			signature.init(privateKeyFormat)
			signature.updateString(code)
			let result = signature.sign()
			axios({
				url: `${window.WEATHER_URL_A}/aiplatformdataview/weather/realTime`,
				method: 'get',
				params: {
					cityCode: cityCode,
					ts: time
				},
				headers: {
					'Geovis-Weather': result,
					'Geovis-AppId': '1fbf964d94a94bb895358bcb3a583e65'
				}
			}).then((res) => {
				if (res.data.code == 500) {
					Toast.fail(res.data.msg)
					return
				}
				let weaRes = res.data.data
				this.detailList[0].value = weaRes.windDirect //风向
				this.detailList[1].value = (weaRes.windSpeed || '0') + 'm/s' //风速
				this.detailList[2].value = weaRes.airPressure / 1000 + 'kPa' //气压
				this.detailList[3].value = weaRes.rainfall + 'mm' //降雨量
				this.detailList[4].value = `${weaRes.minTemp}-${weaRes.maxTemp}℃`
				this.detailList[5].value = weaRes.weatherStatus //天气
				this.detailList[6].value = weaRes.humidity + '%' //相对湿度
				this.detailList[7].value = weaRes.airQuality //空气质量
				this.tRange.low = weaRes.minTemp //最低气温
				this.tRange.height = weaRes.maxTemp //最高气温
				this.humidity = weaRes.humidity + '%'
				this.imgUrl = this.imgurlChose(res.data.data.weatherStatus)
				this.weatherType = weaRes.weatherStatus
				this.currentPlace = weaRes.cityName
			})
		},
		imgurlChose(chn) {
			switch (chn) {
				case '晴':
					return '/img/weather/qing.png'
				case '多云':
					return '/img/weather/duoyun.png'
				case '大雪':
					return '/img/weather/daxue.png'
				case '大雨':
					return '/img/weather/dayu.png'
				case '小雪':
					return '/img/weather/xiaoxue.png'
				case '小雨':
					return '/img/weather/xiaoyu.png'
				case '阴':
					return '/img/weather/yin.png'
				case '中雪':
					return '/img/weather/zhongxue.png'
				case '中雨':
					return '/img/weather/zhongyu.png'
				default:
					return '/img/weather/-.png'
			}
		},
		poiImgChoose(group, type) {
			let ppGroup = ''
			let ppType = ''
			switch (group) {
				case '避难场所':
					ppGroup = 'binan'
					break
				case '防护目标':
					ppGroup = 'fanghu'
					break
				case '救援力量':
					ppGroup = 'jiuyuan'
					break
				case '应急资源':
					ppGroup = 'yingji'
					break
			}
			switch (type) {
				case '避难场所':
					ppType = 'binanchangsuo'
					break
				case '地震避难点':
					ppType = 'dizhenbinandian'
					break
				case '转移安置点':
					ppType = 'zhuanyianzhidian'
					break
				case '变电站':
					ppType = 'biandianzhan'
					break
				case '加油站':
					ppType = 'jiayouzhan'
					break
				case '交通场所':
					ppType = 'jiaotongchangsuo'
					break
				case '天然气站':
					ppType = 'tianranqizhan'
					break
				case '通讯基站':
					ppType = 'tongxunjizhan'
					break
				case '学校分布':
					ppType = 'xuexiaofenbu'
					break
				case '扑火队伍':
					ppType = 'puhuoduiwu'
					break
				case '森林防火队伍':
					ppType = 'senlinfanghuoduiwu'
					break
				case '社会救援组织':
					ppType = 'shehuijiuyuanzuzhi'
					break
				case '消防队伍':
					ppType = 'xiaofangduiwu'
					break
				case '大型物资储存仓库':
					ppType = 'daxingwuzicangku'
					break
				case '物资仓库':
					ppType = 'wuzicangku'
					break
				case '物资储存点':
					ppType = 'chucundian'
					break
				case '医疗机构分布':
					ppType = 'yiliaojigou'
					break
			}
			return `/img/poi/${ppGroup}_${ppType}.png`
		},
		popDown() {
			if (this.popupHeight == '50%') {
				this.popupHeight = '1%'
			} else {
				this.popupHeight = '50%'
			}
		},
		// 初始化ws
		initWebSocket() {
			const wsuri = window.wsURL
			this.websock = new WebSocket(wsuri)
			this.websock.onmessage = this.websocketonmessage
			this.websock.onopen = this.websocketonopen
			this.websock.onerror = this.websocketonerror
			this.websock.onclose = this.websocketclose
		},
		// ws连接成功
		websocketonopen() {
			console.log('ws连接成功')
			this.websocketsend()
			this.pictLoading = false
		},
		// ws失败重连
		websocketonerror() {
			if (this.reConnect < 3) {
				this.initWebSocket()
				this.reConnect++
			} else {
				Toast.fail('连接失败')
			}
		},
		// ws信息接收
		websocketonmessage(e) {
			// return;
			let data = JSON.parse(e.data)
			// 替换
			this.total = data.total
			this.fireAllInfo = data
			this.receiveData(data)
		},
		// ws信息发送
		websocketsend(data) {
			// let data = this.screenData
			// console.log(data)
			if (data == null || !data.hour) {
				this.newIcon = true
				this.websock.send(
					JSON.stringify({
						hour: '1',
						pageNum: '1',
						pageSize: '30',
						startTime: '',
						endTime: '',
						code: '',
						type: '',
						intensityT: '',
						region: ''
					})
				)
			} else {
				this.newIcon = false
				this.websock.send(
					JSON.stringify({
						hour: data.startTime ? '-1' : data.hour,
						pageNum: '1',
						pageSize: '30',
						startTime: data.startTime ? data.startTime : '',
						endTime: data.endTime ? data.endTime : '',
						code: '',
						type: decodeURI(data.stype),
						intensityT: '',
						region: decodeURI(data.region)
					})
				)
			}
		},
		// ws关闭连接
		websocketclose(e) {
			console.log('ws断开连接', e)
		},
		// 信息接收
		receiveData(newValue) {
			let earthList = []
			this.clearAll()
			// 转换格式，存储变量
			newValue.rows.forEach((ele) => {
				let obj = {}
				obj.id = ele.id
				obj.total = ele.introVOList.length
				obj.time = ele.data_time
				obj.list = []
				ele.introVOList.forEach((item) => {
					let obj2 = {}
					obj2.id = item.id
					obj2.title = item.location
					obj2.type = item.vegType
					obj2.code = item.code
					obj2.longitude = item.longitude
					obj2.latitude = item.latitude
					obj2.imgName = this.changeImgName(item.vegType)
					obj2.imgName2 = this.newIcon ? 'huodian.png' : this.changeImgName(item.vegType)
					obj.list.push(obj2)
					earthList.push(obj2)
				})
				this.fireList.push(obj)
			})
			this.dataToEarth(earthList)
		},
		// 清除
		clearAll() {
			// 清除球上的点
			for (var i = 0; i < entityModel.length; i++) {
				viewer.entities.remove(entityModel[i])
			}
			entityModel = []
			// 清除列表
			this.fireList = []
		},
		// 格式化图片
		changeImgName(data) {
			let imgName
			switch (data) {
				case '森林': {
					imgName = 'senlin.png'
					break
				}
				case '草地': {
					imgName = 'caodi.png'
					break
				}
				case '农田及自然植被': {
					imgName = 'nongtian.png'
					break
				}
				case '灌木': {
					imgName = 'guanmu.png'
					break
				}
				case '城市或荒漠': {
					imgName = 'chengshi.png'
					break
				}
			}
			return imgName
		},
		getCityCode(city) {
			let codeDic = [
				{ code: '101310101', city: '海口市' },
				{ code: '101310205', city: '儋州市' },
				{ code: '101310222', city: '五指山市' },
				{ code: '101310212', city: '文昌市' },
				{ code: '101310211', city: '琼海市' },
				{ code: '101310215', city: '万宁市' },
				{ code: '101310202', city: '东方市' },
				{ code: '101310209', city: '定安县' },
				{ code: '101310210', city: '屯昌县' },
				{ code: '101310204', city: '澄迈县' },
				{ code: '101310203', city: '临高县' },
				{ code: '101310207', city: '白沙黎族自治县' },
				{ code: '101310206', city: '昌江黎族自治县' },
				{ code: '101310221', city: '乐东黎族自治县' },
				{ code: '101310216', city: '陵水黎族自治县' },
				{ code: '101310214', city: '保亭黎族苗族自治县' },
				{ code: '101310208', city: '琼中黎族苗族自治县' },
				{ code: '101310201', city: '三亚市' },
				{ code: '101310301', city: '三沙市' }
			]
			let code = codeDic.filter((ele) => ele.city === city)[0].code
			return code
		},
		// 点位上球
		dataToEarth(data) {
			entityModel = []
			//添加标记
			for (let item of data) {
				let entity = viewer.entities.add({
					name: item.title + item.id,
					id: item.id,
					latitude: item.latitude,
					longitude: item.longitude,
					position: Cesium.Cartesian3.fromDegrees(item.longitude, item.latitude),
					billboard: {
						image: `./img/fireIcon/${item.imgName2}`,
						horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
						verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
						heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
						width: 30,
						height: 30,
						scaleByDistance: new Cesium.NearFarScalar(10000, 1.5, 100000, 1),
						disableDepthTestDistance: Number.POSITIVE_INFINITY
					},
					entityType: 'fire'
				})
				entityModel.push(entity)
			}
		},
		// 拾取
		async pickeFireEvent(movement) {
			let that = this
			let pickedObject = viewer.scene.pick(movement.position)
			if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && pickedObject.id.entityType === 'fire') {
				that.showDetail(pickedObject.id)
			} else if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && pickedObject.id.entityType === 'poi') {
				let res = await searchPoiDetail(pickedObject.id.id)
				that.poiDetail = keyFormate(pickedObject.id.name, res)
				// console.log(pickedObject.id.name)
				that.showPoiDetail = true
			} else {
				console.log('none')
			}
		},
		getPdf() {
			let id = this.detailObj.id
			openLink({
				url: `${window.selfURL}bulletin?appId=huoqing-e9Zlo4q8P45M47CrnaeERj&type=1&id=${id}&scopeValue=${this.scopeValue}`
			}).then((res) => {
				console.log(res)
			})
			// // 下载PDF-后端,钉钉不支持手机端下载
			// this.pdfShow = true
			// 	let obj = {}
			// 	obj.angle = this.detailObj.direction + '°'
			// 	obj.distance = this.detailObj.distance + 'Km'
			// 	obj.fireCode = this.detailObj.code
			// 	obj.fireId = this.detailObj.id
			// 	obj.height = this.detailObj.elevationAver + 'm'
			// 	obj.hotNum = this.detailObj.hotspot
			// 	if (!this.detailObj.checkRes || (!this.detailObj.checkRes.death && !this.detailObj.checkRes.hurt && !this.detailObj.checkRes.miss)) {
			// 		obj.hurt = '不明'
			// 	} else {
			// 		let death = this.detailObj.checkRes.death ? this.detailObj.checkRes.death + '人' : '不明'
			// 		let hurt = this.detailObj.checkRes.hurt ? this.detailObj.checkRes.hurt + '人' : '不明'
			// 		let miss = this.detailObj.checkRes.miss ? this.detailObj.checkRes.miss + '人' : '不明'
			// 		obj.hurt = `死亡${death}, 受伤${hurt}, 失踪${miss}`
			// 	}
			// 	obj.lat = this.detailObj.latitude
			// 	obj.lon = this.detailObj.longitude
			// 	obj.phone = this.template.phone
			// 	obj.place = this.detailObj.place
			// 	obj.poiRadius = this.scopeValue * 1000
			// 	obj.reportCode = this.template.reportCode
			// 	obj.reportDate = this.template.reportTime
			// 	obj.reportTitle = this.template.headerBig
			// 	obj.reportUnit = this.template.reportUnit
			// 	obj.reporter = this.template.reporter
			// 	obj.stId = null
			// 	obj.time = this.detailObj.observeTime.replace('-', '年').replace('-', '月').replace(' ', '日 ').replace(':', '时').replace(':', '分') + '秒'
			// 	let all = this.detailObj.gfAver ? this.detailObj.gfAver + '%' : '未知'
			// 	let senlin = this.detailObj.forestPercent ? this.detailObj.forestPercent + '%' : 0
			// 	let caodi = this.detailObj.lawnPercent ? this.detailObj.lawnPercent + '%' : 0
			// 	let nongtian = this.detailObj.farm ? this.detailObj.farm + '%' : 0
			// 	let guanmu = this.detailObj.bush ? this.detailObj.bush + '%' : 0
			// 	let chengshi = this.detailObj.city ? this.detailObj.city + '%' : 0
			// 	let veg = `植被覆盖度${all}, 其中森林${senlin},草地${caodi},农田及自然植被${nongtian},灌木${guanmu},城市或荒漠${chengshi}`
			// 	obj.veg = veg
			// 	obj.words = '无'
			// 	createFile(obj).then((res) => {
			// 		// window.open(`${window.fireURL}/api/special-report/download/${res}`, '_blank')
			// 		//钉钉下载文件，android和ios无法使用
			// 		// dd.downloadFile({
			// 		// 	url: `${window.baseURL}/api/special-report/download/${res}`,
			// 		// 	name: '火情简报.pdf',
			// 		// 	onProgress(res) {
			// 		// 		// 进度返回数据
			// 		// 		// {
			// 		// 		//     doneSize: string;
			// 		// 		//     fileName: string;
			// 		// 		//     filePath: string;
			// 		// 		//     fileSize: string;
			// 		// 		//     speed: number;
			// 		// 		// }
			// 		// 	}
			// 		// })
			// 	})
		}
	}
}
</script>

<style lang="scss">
.fire-box {
	.weather-box {
		position: absolute;
		left: 0.2rem;
		top: 1.5rem;
		width: 0.8rem;
		height: 0.8rem;
		background: rgba($color: #ffffff, $alpha: 0.55);
		border-radius: 0.22rem;
		img {
			width: 0.8rem;
			height: 0.8rem;
			margin: 0 auto;
		}
	}
	.button-box {
		position: absolute;
		right: 0.1rem;
		top: 1.6rem;
		.right-button {
			width: 1.2rem;
			height: 1.2rem;
			background-size: 100% 100%;
			line-height: 1.7rem;
			font-size: 0.2rem;
		}
		.select {
			background-image: url('/img/fire/shaixuan.png');
			margin-bottom: 0.18rem;
		}
		.list {
			background-image: url('/img/fire/liebiao.png');
		}
		.listactive {
			background-image: url('/img/fire/liebiaoactive.png');
			color: #3296fa;
		}
	}
	.van-popup--center {
		// padding-top: 2rem;
		width: 60%;
		height: 50%;
		.poi-title {
			height: 0.8rem;
			line-height: 0.8rem;
			font-size: 0.36rem;
		}
		.van-popup__close-icon--top-right {
			top: 0.2rem;
		}
		.PoiInfoItem {
			div {
				line-height: 0.5rem;
			}
		}
		.weather-content {
			.detail {
				display: flex;
				flex-wrap: wrap;
				// justify-content: space-around;
				.detailItem {
					width: 33%;
					margin-bottom: 0.26rem;
					img {
						width: 0.56rem;
						height: 0.56rem;
						margin: 0.08rem;
					}
				}
			}
		}
	}
	.detailPopup {
		padding-top: 1rem;
		text-align: left;
		background: #f4f4f4;
		.popup-name {
			position: absolute;
			top: 0;
			background: #ffffff;
			font-size: 0.32rem;
			width: 100%;
			text-align: center;
			font-weight: 550;
			color: #1f1f1f;
			line-height: 1rem;
			border-bottom: 1px solid rgba($color: #1f1f1f, $alpha: 0.09);
		}
		.fire-list {
			.van-collapse {
				.van-collapse-item {
					.van-cell {
						background: #f4f4f4;
						.van-cell__title {
							.added {
								display: inline-block;
								width: 0.48rem;
								height: 0.48rem;
								margin-right: 0.2rem;
								font-size: 0.24rem;
								line-height: 0.48rem;
								text-align: center;
								color: #ffffff;
								background: #e85a4a;
							}
						}
					}
					.van-collapse-item__wrapper {
						.van-collapse-item__content {
							background: #f4f4f4;
							.list-content {
								height: 2rem;
								width: 100%;
								background: #ffffff;
								margin-bottom: 0.28rem;
								display: flex;
								align-items: center;
								.content-img {
									width: 1.12rem;
									height: 1.28rem;
									// background-image: url('/img/fire/huodian.png');
									// background-size: 100% 100%;
									margin-left: 0.32rem;
									margin-right: 0.28rem;
									img {
										width: 100%;
										height: 100%;
									}
								}
								.content-font {
									width: calc(100% - 1.2rem - 1.12rem - 0.9rem);
									font-size: 0.22rem;
									margin-right: 0.28rem;
									overflow: hidden;
									.font-title {
										font-size: 0.28rem;
										font-weight: 550;
										margin-bottom: 0.2rem;
										color: #1f1f1f;
									}
								}
								.content-handle {
									width: 0.9rem;
									display: flex;
									flex-direction: column;
									align-items: flex-end;
									.position {
										width: 0.6rem;
										height: 0.6rem;
										margin-bottom: 0.6rem;
									}
									.detail {
										font-size: 0.22rem;
										img {
											width: 0.3rem;
											height: 0.3rem;
										}
									}
								}
							}
							:last-child {
								margin-bottom: 0;
							}
						}
					}
				}
			}
		}

		.fire-detail {
			.detail-panel {
				background: #ffffff;
				padding: 0.3rem 0.4rem;
				// margin-bottom: 0.2rem;
				p {
					font-size: 0.28rem;
					color: #1f1f1f;
					font-weight: 500;
					line-height: 0.4rem;
					margin-bottom: 0.18rem;
				}
				&:first-child {
					margin-bottom: 0.2rem;
				}
			}
			.charge-person {
				margin-bottom: 0.2rem;
			}
			.detail-handel {
				background: #ffffff;
				display: flex;
				justify-content: space-between;
				border-top: 1px solid rgba($color: #1f1f1f, $alpha: 0.09);
				padding: 0.17rem 0.32rem;
				div {
					width: 30%;
					height: 0.9rem;
					border-radius: 0.08rem;
					background: #3296fa;
					color: #ffffff;
					line-height: 0.9rem;
					font-size: 0.34rem;
					text-align: center;
				}
			}
		}
		.assistant-analysis {
			.popDown {
				position: absolute;
				top: 0.3rem;
				left: 0.3rem;
				font-size: 0.4rem;
			}
			.detail-panel {
				background: #ffffff;
				padding: 0.3rem 0.4rem;
				// margin-bottom: 0.2rem;
				p {
					font-size: 0.28rem;
					color: #1f1f1f;
					font-weight: 500;
					line-height: 0.4rem;
					margin-bottom: 0.18rem;
				}
				&:first-child {
					margin-bottom: 0.2rem;
				}
			}
			.check-box-group {
				background: #ffffff;
				margin-top: 0.2rem;
				padding: 0.3rem 0.4rem;
				.each-item {
					margin-bottom: 0.3rem;
					.group-title {
						margin-bottom: 0.18rem;
					}
					.van-checkbox-group {
						background: rgba($color: #3296fa, $alpha: 0.1);
						padding: 0.3rem 0 0.3rem 0.3rem;
						.van-checkbox {
							margin-bottom: 0.3rem;
						}
						:last-child {
							margin-bottom: 0;
						}
					}
				}
			}
			.brief-report-box {
				padding: 0.13rem 0.32rem;
				background: #ffffff;
				.report-button {
					width: 100%;
					height: 0.88rem;
					font-size: 0.34rem;
					text-align: center;
					color: #ffffff;
					line-height: 0.88rem;
					border-radius: 0.08rem;
					background: #3296fa;
				}
			}
		}
	}
}
#cesiumContainer {
	// width: calc(100% - 0.2rem);
	height: 100%;
	width: 100%;
	position: absolute;
	z-index: 0;
	// top: 0.1rem;
	// left: 0.1rem;
}
</style>